#include <stdlib.h>
#include <string.h>

#include <debug.h>
#include <os_api.h>
#include <net/mqttclient.h>

#define TASK_STACK_SIZE (10 * 1024)

#define DEV_CLIENT_ID_LEN 128
#define DEV_HOSTNAME_LEN 128

#define MQTT_USER_NAME_LEN 64
#define MQTT_PASSWORD_LEN 64
#define MQTT_TOPIC_MAX_LEN 64
#define MQTT_PAYLOAD_MAX_LEN 512

static mqtt_client_t *g_client = NULL;

static void sub_topic_handle(void *client, message_data_t *msg)
{
    (void)client;
    LOG_PRINTF("-----------------------------------------------------------------------------------");
    LOG_PRINTF("%s()... topic: %s,message:%s", __FUNCTION__, msg->topic_name, (char *)msg->message->payload);
    LOG_PRINTF("-----------------------------------------------------------------------------------");
}

static int mqtt_publish_handle(mqtt_client_t *client)
{
    int rc;
    mqtt_message_t msg;
    memset(&msg, 0, sizeof(msg));

    msg.qos = QOS0;
    msg.payload = (void *)"this is a kawaii mqtt test ...";
    LOG_PRINTF("%s() mqtt_publish message:%s", __FUNCTION__, msg.payload);

    rc = mqtt_publish(client, "rtt-topic", &msg);
    if (rc != KAWAII_MQTT_SUCCESS_ERROR)
    {
        LOG_PRINTF("%s() mqtt_publish fail:%d", __FUNCTION__, rc);
    }
    return rc;
}

static void mqtt_sample(void *param)
{
    int rc;

    sleep(20);

    LOG_PRINTF("%s()... mqtt test begin...", __FUNCTION__);

    g_client = mqtt_lease();
    if (g_client == NULL)
    {
        LOG_PRINTF("%s() mqtt_lease fail", __FUNCTION__);
        return;
    }

    g_client->mqtt_host = "test.mosquitto.org";
    g_client->mqtt_port = "1883";
    g_client->mqtt_client_id = "asr-mqtt-test";
    g_client->mqtt_clean_session = 1;

    rc = mqtt_connect(g_client);
    if (rc != KAWAII_MQTT_SUCCESS_ERROR)
    {
        LOG_PRINTF("%s() mqtt_connect fail:%d", __FUNCTION__, rc);
        return;
    }
    mqtt_subscribe(g_client, "testtopic", QOS0, sub_topic_handle);
    if (rc != KAWAII_MQTT_SUCCESS_ERROR)
    {
        LOG_PRINTF("%s() mqtt_subscribe fail:%d", __FUNCTION__, rc);
    }

    while (1)
    {
        mqtt_publish_handle(g_client);
        sleep(60);
    }
}

int main(void)
{
    int ret;
    OSTaskRef task_ref; // because following task will never exit, so we do not use task handle, so we don't care it's handle

    ret = OSATaskCreate(&task_ref, NULL, TASK_STACK_SIZE, OS_APP_PRIORITY, "app", mqtt_sample, NULL);
    ASSERT(ret == OS_SUCCESS);
    return 0;
}
